﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Net;
using System.Web;
using System.Web.Mvc;
using WikeSoft.Core.Extension;

using WikeSoft.Enterprise.Interfaces.Sys;
using WikeSoft.Enterprise.Models.Sys;
using WikeSoft.Global;

namespace WikeSoft.Web.Controllers.Sys
{
    public class AttachmentController : Controller
    {

        private readonly IAttachmentService _attachmentService;



        public AttachmentController(IAttachmentService attachmentService)
        {
            this._attachmentService = attachmentService;
        }


        public ActionResult UploadFile()
        {
            AttachmentModel ret = null;

            string[] urls = null;
            if (ConfigurationManager.AppSettings["FileAppName"].IsBlank())
            {
                throw new Exception("not config FileAppName");
            }

            if (ConfigurationManager.AppSettings["FileGroupName"].IsBlank())
            {
                throw new Exception("not config FileGroupName");
            }
            bool isimg = false;
            string filename = String.Empty;
            string contentType = string.Empty;
            HttpPostedFileBase file = Request.Files[0];
            if (file != null && file.ContentLength > 0)
            {
                filename = file.FileName;
                //contentType = file.ContentType;
                //如果是falsh上传的，file.ContenType 无论什么名称都是application/octet-stream，通过 MimeMapping解决此问题
                //MimeMapping最低要求.net 4.5
                contentType = MimeMapping.GetMimeMapping(filename);
                var extension = Path.GetExtension(file.FileName);
                if (extension != null)
                {
                    String ext = extension.ToLower();
                    isimg = file.FileName.IsImage();

                    if (isimg)
                    {
                        FileEntity fl = new FileEntity()
                        {
                            AppName = ConfigurationManager.AppSettings["FileAppName"],
                            Group = ConfigurationManager.AppSettings["FileGroupName"],
                            IsCompressImage = true,
                            FileType = ext,
                            Contents = new byte[file.ContentLength],
                            IsImageFile = file.FileName.IsImage(),
                            CompressWidth = String.IsNullOrEmpty(ConfigurationManager.AppSettings["ImgCompressWidth"])?Convert.ToInt32(ConfigurationManager.AppSettings["ImgCompressWidth"]):100

                        };
                        file.InputStream.Read(fl.Contents, 0, file.ContentLength);
                        urls = FileProcess.UploadFile(fl);
                    }
                    else
                    {
                        FileEntity fl = new FileEntity()
                        {
                            AppName = ConfigurationManager.AppSettings["FileAppName"],
                            Group = ConfigurationManager.AppSettings["FileGroupName"],
                            IsCompressImage = false,
                            FileType = ext,
                            Contents = new byte[file.ContentLength],
                            IsImageFile = file.FileName.IsImage()

                        };
                        file.InputStream.Read(fl.Contents, 0, file.ContentLength);
                        urls = FileProcess.UploadFile(fl);

                    }

                }
            }

            if (urls.Length > 1)
            {
                ret = _attachmentService.InsertAttachment(urls[0], urls[1], isimg, filename, contentType);
            }
            else
            {
                ret = _attachmentService.InsertAttachment(urls[0], string.Empty, isimg, filename, contentType);
            }
            return Json(ret, JsonRequestBehavior.AllowGet);
        }



        //public ActionResult UploadFile(string id, string name, string type, string lastModifiedDate, int size, HttpPostedFileBase file)
        //{
        //    AttachmentModel ret = null;

        //    string[] urls = null;
        //    if (ConfigurationManager.AppSettings["FileAppName"].IsBlank())
        //    {
        //        throw new Exception("not config FileAppName");
        //    }

        //    if (ConfigurationManager.AppSettings["FileGroupName"].IsBlank())
        //    {
        //        throw new Exception("not config FileGroupName");
        //    }
        //    bool isimg = false;
        //    string filename = String.Empty;
        //    string contentType = string.Empty;
        //    //HttpPostedFileBase file = Request.Files[0];
        //    if (file != null && file.ContentLength > 0)
        //    {
        //        filename = file.FileName;
        //        contentType = file.ContentType;
        //        var extension = Path.GetExtension(file.FileName);
        //        if (extension != null)
        //        {
        //            String ext = extension.ToLower();
        //            isimg = file.FileName.IsImage();

        //            if (isimg)
        //            {
        //                FileEntity fl = new FileEntity()
        //                {
        //                    AppName = ConfigurationManager.AppSettings["FileAppName"],
        //                    Group = ConfigurationManager.AppSettings["FileGroupName"],
        //                    IsCompressImage = true,
        //                    FileType = ext,
        //                    Contents = new byte[file.ContentLength],
        //                    IsImageFile = file.FileName.IsImage(),
        //                    CompressWidth = 500

        //                };
        //                file.InputStream.Read(fl.Contents, 0, file.ContentLength);
        //                urls = FileProcess.UploadFile(fl);
        //            }
        //            else
        //            {
        //                FileEntity fl = new FileEntity()
        //                {
        //                    AppName = ConfigurationManager.AppSettings["FileAppName"],
        //                    Group = ConfigurationManager.AppSettings["FileGroupName"],
        //                    IsCompressImage = false,
        //                    FileType = ext,
        //                    Contents = new byte[file.ContentLength],
        //                    IsImageFile = file.FileName.IsImage()

        //                };
        //                file.InputStream.Read(fl.Contents, 0, file.ContentLength);
        //                urls = FileProcess.UploadFile(fl);

        //            }

        //        }
        //    }

        //    if (urls.Length > 1)
        //    {
        //        ret = _attachmentService.InsertAttachment(urls[0], urls[1], isimg, filename, contentType);
        //    }
        //    else
        //    {
        //        ret = _attachmentService.InsertAttachment(urls[0], string.Empty, isimg, filename, contentType);
        //    }
        //    return Json(ret, JsonRequestBehavior.AllowGet);
        //}

        public ActionResult DeleteAttachment(string id)
        {
            AttachmentModel data = _attachmentService.Find(id);
            List<string> urls = new List<string>();
            urls.Add(data.UrlPath);
            if (data.ThumUrlPath.IsNotBlank())
            {
                urls.Add(data.ThumUrlPath);
            }
            OperateResult result = FileProcess.DeleteFile(urls);
            if (result.Success)
            {
                _attachmentService.Delete(id);
                return Json(new {success = true}, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(new { success = false, message="操作失败" }, JsonRequestBehavior.AllowGet);
            }
            
        }

        public ActionResult ClearNoUse()
        {
            List<AttachmentModel> list = _attachmentService.GetNotUsedList();
            foreach (var data in list)
            {
                List<string> urls = new List<string>();
                urls.Add(data.UrlPath);
                if (data.ThumUrlPath.IsNotBlank())
                {
                    urls.Add(data.ThumUrlPath);
                }
                OperateResult result = FileProcess.DeleteFile(urls);
            }

            return Json(new { success = true }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult DownLoad(string id)
        {

            AttachmentModel data = _attachmentService.Find(id);

            try
            {
                string contentype = WebRequest.Create(data.UrlPath).GetResponse().ContentType;
                byte[] buff = downloadData(data.UrlPath);
                Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", data.TrueName));
                return new FileContentResult(buff, contentype);

            }
            catch (Exception)
            {
                // ignored
            }

            return null;
        }

        private byte[] downloadData(string url)
        {
            byte[] downloadedData = new byte[0];
            try
            {
                //Optional


                //Get a data stream from the url
                WebRequest req = WebRequest.Create(url);
                WebResponse response = req.GetResponse();
                Stream stream = response.GetResponseStream();

                //Download in chuncks
                byte[] buffer = new byte[1024];

                //Get Total Size
                int dataLength = (int)response.ContentLength;

                //With the total data we can set up our progress indicators


                //Download to memory
                //Note: adjust the streams here to download directly to the hard drive
                MemoryStream memStream = new MemoryStream();
                while (true)
                {
                    //Try to read the data
                    int bytesRead = stream.Read(buffer, 0, buffer.Length);

                    if (bytesRead == 0)
                    {
                        break;
                    }
                    else
                    {
                        memStream.Write(buffer, 0, bytesRead);
                    }
                }
                downloadedData = memStream.ToArray();
                stream.Close();
                memStream.Close();
            }
            catch (Exception)
            {


            }

            return downloadedData;
        }
    }
}